﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using TestBat.IModels.Models;
using TestBat.IViewModels.Base;
using TestBat.IViewModels.Factories;
using TestBat.IViewModels.Workspaces.Tasks;
using TestBat.ViewModels.Attributes;
using TestBat.ViewModels.Base;

namespace TestBat.ViewModels.Workspaces.Tasks
{
    public class TaskTreeViewModel : ViewModel, ITaskTreeViewModel
    {
        public TaskTreeViewModel(ITaskFolderModel taskFolderModel, IRootTaskFolderViewModelFactory rootTaskFolderViewModelFactory)
        {
            this.taskFolderModel = taskFolderModel;
            this.rootTaskFolderViewModelFactory = rootTaskFolderViewModelFactory;
        }

        [BusinessErrorDialog]
        public ReadOnlyCollection<ITaskFolderViewModel> Root
        {
            get
            {
                if (root == null)
                {
                    // create the root folder
                    ITaskFolderViewModel tmp = rootTaskFolderViewModelFactory.Create(taskFolderModel.GetRootFolder());
                    tmp.PreSelect = delegate(ITreeItemViewModel treeItem) { SelectedItem = treeItem; };
                    var tmpList = new List<ITaskFolderViewModel>();
                    tmpList.Add(tmp);
                    root = new ReadOnlyCollection<ITaskFolderViewModel>(tmpList);
                }

                return root;
            }
        }

        public ITreeItemViewModel SelectedItem
        {
            get { return selectedItem; }
            set
            {
                if (selectedItem != value)
                    ChangeSelectedItem(value);
            }
        }


        [CheckUnsavedChanges]
        protected virtual void ChangeSelectedItem(ITreeItemViewModel to)
        {
            if (selectedItem != null)
                selectedItem.OnLostFocus();

            selectedItem = to;

            NotifyPropertyChanged(() => this.SelectedItem);
        }

        protected ITreeItemViewModel selectedItem;

        private readonly ITaskFolderModel taskFolderModel;

        private ReadOnlyCollection<ITaskFolderViewModel> root;

        private readonly IRootTaskFolderViewModelFactory rootTaskFolderViewModelFactory;
    }
}
